// app/service/user.js
const Service = require("egg").Service;
const fs = require("fs-extra");
const p = require("path");
const { Op } = require("sequelize");
const _ = require("loadsh");
const needle = require("needle");

class WebService extends Service {
  async searchByPreset(params) {
    let { value } = params;
    let ret = await this.ctx.model.MovieData.findAll({
      where: {
        name: {
          [Op.like]: `%${value}%`,
        },
      },
      limit: 10,
      offset: 1,
    });

    return { data: { rows: ret }, msg: "获取电影数据预设成功" };
  }

  async updateInfo(params) {
    try {
      await this.ctx.model.Movie.update(
        { ...params },
        {
          where: {
            id: params.id,
          },
        }
      );
      return { msg: "获取电影信息成功" };
    } catch (e) {
      return { msg: "获取电影信息失败", code: 400 };
    }
  }

  async getClassify(params) {
    try {
      let where = {};
      if (params?.show != undefined) {
        where.show = params.show;
      }
      let ret = await this.ctx.model.MovieClass.findAll({ where });
      return { data: ret, msg: "获取电影分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电影分类失败", code: 400 };
    }
  }
  async addClassify(params) {
    try {
      let ret = await this.ctx.model.MovieClass.create({ ...params });
      return { data: ret, msg: "添加电影分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "添加电影分类失败", code: 400 };
    }
  }
  async deleteClassify(params) {
    try {
      await this.ctx.model.MovieClass.destroy({
        where: {
          id: params.id,
        },
      });
      return { msg: "删除电影分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "删除电影分类失败", code: 400 };
    }
  }
  async updateClassify(params) {
    try {
      await this.ctx.model.MovieClass.update(
        { ...params },
        {
          where: {
            id: params.id,
          },
        }
      );
      return { msg: "更新电影分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "更新电影分类失败", code: 400 };
    }
  }
  async addMovie(params) {
    let { movie_data, file_path, save_type, data_type } = params;
    let result = { data: {}, msg: "保存数据成功", code: 200 };
    let isHas = await this.ctx.model.Movie.findOne({
      where: { word: movie_data.word },
    });
    if (isHas != null) {
      result.msg = "您添加的电影已存在，请不要重复添加";
      result.code = 400;
      return result;
    }
    if (data_type != "input") {
      let picRet = await needle("get", movie_data.pic);
      let name = movie_data.word + ".png";
      let savePath = p.join(this.config.space.movie_img_space, name);
      fs.writeFileSync(savePath, picRet.body);
      movie_data.pic = name;
    }
    let movie_ret = await this.ctx.model.Movie.create({
      ...movie_data,
      link: movie_data.word + p.extname(file_path),
    });
    this.disposeMovieFile(file_path, movie_data.word);
    return { msg: "保存数据成功", code: 200 };
  }
  disposeMovieFile(file_path, file_name) {
    let { config, app } = this;
    let target = p.join(
      config.space.movie_path,
      file_name + p.extname(file_path)
    );
    let readStream = fs.createReadStream(file_path);
    let writeStream = fs.createWriteStream(target);
    readStream.pipe(writeStream);
    readStream.on("end", async () => {
      console.log("文件已经复制");
      console.log(`任务 ${file_name} 完成`);
    });
  }

  async deleteMovie(params) {
    let { id, name, link } = params;
    let target = p.join(this.config.space.movie_path, link);
    try {
      await this.ctx.model.Movie.destroy({
        where: {
          id,
        },
      });
      fs.unlinkSync(target);
      await this.app.model.Notifi.create({
        title: "删除操作",
        content: `删除电影 ${name} 任务完成`,
      });
      return { msg: "删除电影数据成功" };
    } catch (e) {
      console.log(e);
      return { msg: "删除电影数据失败" };
    }
  }

  async getMovieDetail(params) {
    let { id } = params;
    try {
      let ret = await this.ctx.model.Movie.findByPk(id);
      return { data: ret, msg: "获取电影数据成功！" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电影列表失败" };
    }
  }

  async getMovieList(params) {
    let { limit, offset, query } = params;
    let where = {};
    if (query?.show != undefined) {
      where.show = query.show;
    }
    if (query?.name != undefined) {
      where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }
    try {
      let ret = await this.ctx.model.Movie.findAndCountAll({
        where,
        limit,
        offset,
      });

      return { data: ret, msg: "获取电影列表成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电影列表失败" };
    }
  }
}

module.exports = WebService;
